package com.example.javamaday.leetcode;

public class LeetCodeTest0468 {

    public static void main(String[] args) {
        new LeetCodeTest0468().validIPAddress("20EE:FGb8:85a3:0:0:8A2E:0370:7334");
    }

    public String validIPAddress(String ip) {
        if (ip == null || ip.length() < 7) {
            return "Neither";
        }
        if (ip.contains(".") && ip.contains(":")) {
            return "Neither";
        }
        if (ip.contains(".")) {
            if (ip.startsWith(".") || ip.endsWith(".")) {
                return "Neither";
            }
            String[] split = ip.split("\\.");
            if (split.length != 4) {
                return "Neither";
            }
            for (String s : split) {
                try {
                    int parseInt = Integer.parseInt(s);
                    if (parseInt > 255 || parseInt < 0) {
                        return "Neither";
                    }
                    if (s.length() != String.valueOf(parseInt).length()) {
                        return "Neither";
                    }
                } catch (NumberFormatException e) {
                    return "Neither";
                }
            }
            return "IPv4";
        }
        if (ip.contains(":")) {
            if (ip.startsWith(":") || ip.endsWith(":")) {
                return "Neither";
            }
            String[] split = ip.split(":");
            if (split.length != 8) {
                return "Neither";
            }
            for (String s : split) {
                // 校验ipv6的每节是否符合
                if (s.length() <= 0 || s.length() > 4) {
                    return "Neither";
                }
                if (isAllLetters(s)) {
                    continue;
                } else {
                    return "Neither";
                }
            }
            return "IPv6";
        }
        return "Neither";
    }

    //判断一个字符串中是否全为字母
    public static boolean isAllLetters(String str) {
        char[] chars = str.toCharArray();
        boolean isPhontic;
        for (char c : chars) {
            isPhontic = (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || (c >= '0' && c <= '9');
            if (!isPhontic) {
                return false;
            }
        }
        return true;
    }
}
